package com.wohuijituan.whcsmerchant.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.adapter.BankNameAdapter;
import com.wohuijituan.whcsmerchant.bean.BankNameListBean;
import com.wohuijituan.whcsmerchant.bean.IsSuccessBean;
import com.wohuijituan.whcsmerchant.callback.BankNameListCallBack;
import com.wohuijituan.whcsmerchant.callback.IsSuccessCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 说明：
 * 作者：朱世元
 * 时间： 2016/10/12 11:48
 * 版本：V1.0
 * 修改历史：
 */
public class CardAddActivity extends MyBaseActivity implements View.OnClickListener{
    private static final String TAG = "CardAddActivity";
    private TextView etBankName;
    private EditText etCardNumber;
    private EditText etCardName;
    private EditText etBankAddress;
    private EditText etBankNumber;
    private ImageButton titleGoBack;
    private TextView titleName;
    private TextView titleAction;
    private Button btnAddBankCard;
    private void assignViews() {
        titleGoBack = (ImageButton) findViewById(R.id.title_go_back);
        titleName = (TextView) findViewById(R.id.title_name);
        titleAction = (TextView) findViewById(R.id.title_tv_action);
        etBankName = (TextView) findViewById(R.id.et_bank_name);
        etCardNumber = (EditText) findViewById(R.id.et_card_number);
        etCardName = (EditText) findViewById(R.id.et_card_name);
        etBankAddress = (EditText) findViewById(R.id.et_bank_address);
        etBankNumber = (EditText) findViewById(R.id.et_bank_number);
        btnAddBankCard = (Button) findViewById(R.id.btn_add_bank_card);
    }

    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    private static final int BankNameRequest_OK = 7891;
    private static final int BankCardAdd_OK = 7451;
    private BankNameAdapter bankNameAdapter;
    private List<BankNameListBean.DataEntity> bankNameList;
    private BankNameListBean.DataEntity selectBank;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_add);
        assignViews();
        initData();
        initView();
        initListener();
        bankNameRequest();
    }

    private void initData() {
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        bankNameList = new ArrayList<>();
        bankNameAdapter = new BankNameAdapter(ctx,bankNameList);
    }

    private void initView() {
        titleGoBack.setVisibility(View.VISIBLE);
        titleName.setText("添加银行卡");

    }

    private void initListener() {
        titleGoBack.setOnClickListener(this);
        btnAddBankCard.setOnClickListener(this);
        etBankName.setOnClickListener(this);
    }

    /**
     * 弹出弹框,供用户选择所添银行卡归属的银行
     */
    private void selectBankName(){
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            BankNameListBean.DataEntity selectBank = bankNameAdapter.getItem(0);
            @Override
            public void onClick(DialogInterface dialog, int which) {
                LogUtils.e(TAG,"selectWhich:"+which);
                switch (which){
                    case -2:
                        break;
                    case -1:
                        CardAddActivity.this.selectBank = this.selectBank;
                        etBankName.setText(selectBank.getB_Name());
                        break;
                    default:
                        selectBank = bankNameAdapter.getItem(which);
                        bankNameAdapter.setSelPosition(which);
                        break;
                }
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
                .setTitle("请选择银行")
                .setSingleChoiceItems(bankNameAdapter,0,listener)
                .setPositiveButton("确认",listener)
                .setNegativeButton("取消",listener);
        builder.create().show();
    }
    /**
     * 请求银行供用户选择
     */
    private void bankNameRequest(){
        showDialog(ctx);
        String strUrl = Urls.BankNameList;
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        myOkHttpUtils.postRequest(strUrl, params, new BankNameListCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(BankNameListBean response, int id) {
                if (response.getState() == 1 && response.getData().size() != 0) {
                    Message msg = new Message();
                    msg.what = BankNameRequest_OK;
                    msg.obj = response;
                    handler.sendMessage(msg);
                } else if (response.getData().size() == 0) {
                    dismissDialog();
                    showToast(ctx, "数据为空");
                } else {
                    dismissDialog();
                    showToast(ctx, "错误信息:" + response.getMsg());
                }
            }
        });
    }

    /**
     * 添加银行卡
     * @param bankID 后台银行编号
     * @param cardNumber 银行卡列表
     * @param realName 开户人姓名
     * @param contactNumber  开户行银联号
     * @param address 开户行地址
     */
    private void cardAddRequest(
            int bankID,String cardNumber,String realName,String contactNumber,String address){
        showDialog(ctx);
        String strUrl = Urls.BankCardAdd;
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.BankCardAdd_BankID, bankID+"");
        params.addStringRequest(ParamsKey.BankCardAdd_CardNumber, cardNumber);
        params.addStringRequest(ParamsKey.BankCardAdd_UserName, realName);
        params.addStringRequest(ParamsKey.BankCardAdd_ContactNumber,contactNumber);
        params.addStringRequest(ParamsKey.BankCardAdd_Address,address);
        myOkHttpUtils.postRequest(strUrl, params, new IsSuccessCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(IsSuccessBean response, int id) {
                if (response.getState() == 1) {
                    if (response.getData().isIsSuccess()) {
                        handler.sendEmptyMessage(BankCardAdd_OK);
                    } else {
                        showToast(ctx, "错误信息:" + response.getData().getMessage());
                        dismissDialog();
                    }
                } else {
                    showToast(ctx, "错误信息:" + response.getMsg());
                    dismissDialog();
                }
            }
        });

    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case BankNameRequest_OK:
                    //银行名称列表请求成功
                    BankNameListBean bankNameListBean = (BankNameListBean) msg.obj;
                    bankNameAdapter.replace(bankNameListBean.getData());
                    dismissDialog();
                    break;
                case BankCardAdd_OK:
                    //银行卡添加成功
                    setResult(RESULT_OK);
                    finish();
                    dismissDialog();
                    showToast(ctx,"银行卡添加成功");
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add_bank_card:
                // TODO: 2016/10/12 提交添加银行卡申请
                if (selectBank==null){
                    showToast(ctx,"请选择银行");
                    return;
                }
                int bankId = selectBank.getB_ID();
                String cardNumber = etCardNumber.getText().toString().trim();
                if (cardNumber==null){
                    showToast(ctx,"请输入银行卡号");
                    return;
                }
                String userName= etCardName.getText().toString().trim();
                if (userName==null){
                    showToast(ctx,"请填写开户人姓名");
                    return;
                }
                String bankAddress = etBankAddress.getText().toString().trim();
                if (bankAddress==null){
                    showToast(ctx,"请填写开户行地址");
                    return;
                }
                String bankNumber = etBankNumber.getText().toString().trim();
                if (bankNumber==null){
                    showToast(ctx,"请填写开户行的银联号");
                    return;
                }
                cardAddRequest(bankId,cardNumber,userName,cardNumber,bankAddress);
                break;
            case R.id.et_bank_name:
                selectBankName();
                break;
            case R.id.title_go_back:
                //  返回
                onBackPressed();
                break;
        }
    }
}
